/**
 *  @(#)  IFAAAuthenticator  module    1.0  2017/03/24
 *
 *  Copyright  (c)  2017,  IFAA  and/or  its  affiliates.  All  rights  reserved.
 *
 *  Redistribution  and  use  in  source  and  binary  forms,  with  or  without
 *  modification,  are  permitted  provided  that  the  following  conditions  are  met:
 *
 *  -Redistribution  of  source  code  must  retain  the  above  copyright  notice,  this
 *    list  of  conditions  and  the  following  disclaimer.
 *
 *  -Redistribution  in  binary  form  must  reproduce  the  above  copyright  notice,
 *    this  list  of  conditions  and  the  following  disclaimer  in  the  documentation
 *    and/or  other  materials  provided  with  the  distribution.
 *
 *  Neither  the  name  of  IFAA  or  the  names  of  contributors  may
 *  be  used  to  endorse  or  promote  products  derived  from  this  software  without
 *  specific  prior  written  permission.
 *
 *  This  software  is  provided  "AS  IS,"  without  a  warranty  of  any  kind.  ALL
 *  EXPRESS  OR  IMPLIED  CONDITIONS,  REPRESENTATIONS  AND  WARRANTIES,  INCLUDING
 *  ANY  IMPLIED  WARRANTY  OF  MERCHANTABILITY,  FITNESS  FOR  A  PARTICULAR  PURPOSE
 *  OR  NON-INFRINGEMENT,  ARE  HEREBY  EXCLUDED.  IFAA,  ORG.
 *  AND  ITS  LICENSORS  SHALL  NOT  BE  LIABLE  FOR  ANY  DAMAGES  SUFFERED  BY  LICENSEE
 *  AS  A  RESULT  OF  USING,  MODIFYING  OR  DISTRIBUTING  THIS  SOFTWARE  OR  ITS
 *  DERIVATIVES.  IN  NO  EVENT  WILL  IFAA  OR  ITS  LICENSORS  BE  LIABLE  FOR  ANY  LOST
 *  REVENUE,  PROFIT  OR  DATA,  OR  FOR  DIRECT,  INDIRECT,  SPECIAL,  CONSEQUENTIAL,
 *  INCIDENTAL  OR  PUNITIVE  DAMAGES,  HOWEVER  CAUSED  AND  REGARDLESS  OF  THE  THEORY
 *  OF  LIABILITY,  ARISING  OUT  OF  THE  USE  OF  OR  INABILITY  TO  USE  THIS  SOFTWARE,
 *  EVEN  IF  IFAA  HAS  BEEN  ADVISED  OF  THE  POSSIBILITY  OF  SUCH  DAMAGES.
 *
 *  You  acknowledge  that  this  software  is  not  designed,  licensed  or  intended
 *  for  use  in  the  design,  construction,  operation  or  maintenance  of  any
 *  nuclear  facility.
 *
 */
package com.ifaa.sdk.authenticatorservice.fingerprint.ta;

import android.content.Context;

import com.ifaa.sdk.util.ByteUtils;
import com.ifaa.sdk.authenticatorservice.fingerprint.manager.IFAAFingerprintManagerAdapter;
import com.ifaa.sdk.authenticatorservice.fingerprint.util.PackageUtils;
import com.ifaa.sdk.authenticatorservice.message.Result;
import com.ifaa.sdk.auth.message.AuthenticatorResponse;

/**
 * 
 * @author qiyi.wxc
 * @version 1.0
 */

public class TAInterationV1 {

    public static byte[] getHeader(Context context) {
        try {
            byte[] packageSign = PackageUtils.getApkKeyHashBytes(context, context.getPackageName());
            byte[] packageName = context.getPackageName().getBytes();

            int packageSignLength = packageSign.length;
            int packageNameLength = packageName.length;

            byte[] param = new byte[4 + 4 + packageSignLength + 4 + packageNameLength];
            int startPoint = 0;

            // 1 version
            System.arraycopy(ByteUtils.toBytes(1), 0, param, startPoint, 4);
            startPoint += 4;

            // 2 signData
            System.arraycopy(ByteUtils.toBytes(packageSignLength), 0, param, startPoint, 4);
            startPoint += 4;
            System.arraycopy(packageSign, 0, param, startPoint, packageSignLength);
            startPoint += packageSignLength;

            // 3 packageName
            System.arraycopy(ByteUtils.toBytes(packageNameLength), 0, param, startPoint, 4);
            startPoint += 4;
            System.arraycopy(packageName, 0, param, startPoint, packageNameLength);
            startPoint += packageNameLength;

            return param;
        } catch (Exception e) {
            // do nothing
        }
        return null;
    }

    public static Result sendCommand(Context context, int command) {
        byte[] header = getHeader(context);
        if (header == null || header.length == 0) {
            return new Result(AuthenticatorResponse.RESULT_FAILURE, null);
        }

        int headerLength = header.length;
        byte[] param = new byte[headerLength + 4];

        int startPoint = 0;

        // 1 header
        System.arraycopy(header, 0, param, startPoint, headerLength);
        startPoint += headerLength;

        // 2 cmd
        System.arraycopy(ByteUtils.toBytes(command), 0, param, startPoint, 4);
        startPoint += 4;

        byte[] resultBytes = doSendData(context, param);
        Result result = buildResult(resultBytes);
        return result;
    }

    public static Result sendCommandAndData(Context context, int command, byte[] data) {
        if (data == null || data.length == 0) {
            return sendCommand(context, command);
        }

        byte[] header = getHeader(context);
        if (header == null || header.length == 0) {
            return new Result(AuthenticatorResponse.RESULT_FAILURE, null);
        }

        int headerLength = header.length;
        int dataLength = data.length;
        byte[] param = new byte[headerLength + 4 + 4 + dataLength];

        int startPoint = 0;

        // 1 header
        System.arraycopy(header, 0, param, startPoint, headerLength);
        startPoint += headerLength;

        // 2 cmd
        System.arraycopy(ByteUtils.toBytes(command), 0, param, startPoint, 4);
        startPoint += 4;

        // 3 data
        System.arraycopy(ByteUtils.toBytes(dataLength), 0, param, startPoint, 4);
        startPoint += 4;
        System.arraycopy(data, 0, param, startPoint, dataLength);
        startPoint += dataLength;

        byte[] resultBytes = doSendData(context, param);
        Result result = buildResult(resultBytes);
        return result;
    }

    private static byte[] doSendData(Context context, byte[] data) {
        IFAAFingerprintManagerAdapter adapter = IFAAFingerprintManagerAdapter.getInstance(context);

        // invoke command
        return adapter.invokeCmd(data);
    }

    /**
     * build Result from TEEData
     * 
     * @param resultData
     * @return
     */
    private static Result buildResult(byte[] resultData) {
        if (resultData == null || resultData.length < 8) {
            return new Result(AuthenticatorResponse.RESULT_TEE_INVOKE_RETURN_NULL, null);
        }

        byte[] data = new byte[resultData.length - 8];

        ByteUtils.copy(resultData, 8, resultData.length - 8, data, 0);
        Result result = new Result();

        result.setStatus(ByteUtils.toInt(resultData));

        result.setData(data);
        return result;
    }

}
